<template>
  <div class="bg-gray">
    <b-container>
      <b-row>
        <b-col>
          <b-breadcrumb class="bg-gray bread-border">
            <b-breadcrumb-item to="/publish">
              <b-icon icon="list-ul" scale="1.25" shift-v="-1.25"/>
              发布列表
            </b-breadcrumb-item>
            <b-breadcrumb-item active>新建发布</b-breadcrumb-item>
          </b-breadcrumb>
        </b-col>
      </b-row>
      <b-row>
        <b-col cols="12" class="mt-1 text-center">
          <h4>新建发布</h4>

        </b-col>
        <b-col cols="12">
          <b-form-group
              id="fieldset-1"
              label="标题："
              label-for="input-1"
              class="mb-1"
          >
            <b-form-input
                id="input-1"
                v-model="form.title"
                :state="status.title"
                trim
                placeholder="不能为空"
                @blur="validTitle"
            ></b-form-input>
            <b-form-invalid-feedback v-text="warn.title"></b-form-invalid-feedback>
          </b-form-group>
          <b-form-group
            label="价格："
          >
            <b-form inline >
              <b-input-group prepend="价格：￥" class="mb-2 mr-md-2" >
                <b-input id="in" placeholder="价格" type="number" v-model="form.price"></b-input>
              </b-input-group>
              <b-input-group prepend="邮费：￥" class="mb-0 mb-md-2">
                <b-input id="i1n" placeholder="邮费" type="number" v-model="form.postage"></b-input>
              </b-input-group>
            </b-form>
          </b-form-group>

          <b-form-group
              id="fieldset-3"
              label="简介："
              label-for="input-3"
              class="mb-1"
          >
            <b-form-textarea
                id="input-3"
                v-model="form.desc"
                :state="status.desc"
                trim
                rows="4"
                max-rows="6"
                placeholder="不超过140字"
                @blur="validDesc"
            ></b-form-textarea>
            <b-form-invalid-feedback v-text="warn.desc"></b-form-invalid-feedback>
          </b-form-group>
          <b-form-group
              id="fieldset-2"
              label="图片："
              label-for="input-2"
              class="mb-1"
              description="图片大小不得超过5MB"
          >
            <b-form-file
                accept=".jpg, .jpeg, .png, .gif"
                multiple
                placeholder="选择图片"
                drop-placeholder="拖拽图片到这里"
                browse-text="浏览"
                v-model="files"
                :state="status.file"
            ></b-form-file>
          </b-form-group>
          <b-form-invalid-feedback v-text="warn.file"></b-form-invalid-feedback>
          <b-row>
            <b-col cols="12" md="6" v-for="(file,index) in files" class="text-center">
              <img class="max-height" :src="urls[index]"/>
              <p class="m-0 p-0">
                <b-button variant="danger" @click="delFile(index)" class="px-4 my-1">删除</b-button>
              </p>

            </b-col>
          </b-row>
        </b-col>
      </b-row>
      <b-row>
        <b-col cols="12" class="text-center my-3">
          <p class="m-0 p-0 ">
            <b-button variant="info" class="mr-2 px-3" @click="submit(false)">保存</b-button>
            <b-button variant="primary" class="mr-2 px-3" @click="submit">发布</b-button>
            <b-button class="px-3" to="/publish">取消</b-button>
          </p>
        </b-col>
      </b-row>
    </b-container>
  </div>
</template>

<script>
  import urlconfig from "../urlconfig";

  export default {
    name: "PublishNew",
    data() {
      return {
        form: {
          title: '',
          desc: '',
          price:'',
          postage:'',
        },
        status: {
          title: null,
          desc: null,
          file: null
        },
        warn: {
          title: '',
          desc: '',
          file: ''
        },
        files: [],
        urls: [],
      }
    },
    methods: {
      makeToast(msg, res = true) {
        this.$bvToast.toast(msg, {
          title: res ? '操作成功!' : '操作失败！',
          variant: res ? 'primary' : 'danger',
          solid: true,
          autoHideDelay: 5000,
        })
      },
      validTitle() {
        if (this.form.title.length > 40) {
          this.warn.title = '不能超过40字'
          this.status.title = false
          return false
        } else if (this.form.title === '') {
          this.warn.title = '不能为空'
          this.status.title = false
          return false
        } else {
          this.status.title = true
          return true
        }
      },
      validDesc() {
        if (this.form.desc.length > 140) {
          this.warn.desc = '不能超过140字'
          this.status.desc = false
          return false
        } else if (this.form.desc === '') {
          this.warn.desc = '不能为空'
          this.status.desc = false
          return false
        } else {
          this.status.desc = true
          return true
        }
      },
      validPic(){
        if (this.files.length ===0){
          this.warn.file = '图片不能为空'
          this.status.file = false
          return false
        }else{
          this.status.file = true
          return true
        }
      },
      delFile(index) {
        this.files.splice(index, 1)
        this.urls.splice(index, 1)
      },
      imgUrl() {
        //将 input 得到的 img转换成url给src
        if (Boolean(this.files)) {
          for (let index in this.files) {
            if (this.files[index].size > urlconfig.maxSize*1024 * 1024) {
              this.warn.file = '图片大小超过'+urlconfig.maxSize+'MB'
              this.status.file = false
              return
            }

            let reader = new FileReader()

            reader.readAsDataURL(this.files[index])
            reader.onload = ev => {
              this.urls.splice(index, 0, ev.target.result)
            }

            this.status.file = true
          }

          // return this.urls[index]
        }

      },
      submit(pub=true){

        if (this.validDesc()&&this.validTitle()&&this.validPic()){
          let data = new FormData()
          data.append("uuid",this.$store.state.uuid)
          data.append("title",this.$ajax.encode(this.form.title))
          data.append("desc",this.$ajax.encode(this.form.desc))
          data.append("status",pub?1:0)
          data.append("price",this.form.price===''?0:+this.form.price)
          data.append("postage",this.form.postage===''?0:+this.form.postage)
          for (let index in this.files){
            data.append('file',this.files[index])
          }
        this.$ajax.post('/item/newitem',data).then(resp=>{
          let data = resp.data
          this.makeToast(data.msg)
          if (data.code === 200){
            this.$router.push('/publish')
          }
        }).catch(err=>{
          this.makeToast("请求失败",false)
          console.log(err);
        })


        }
      }

    },
    computed: {},
    watch: {
      files: function () {
        this.imgUrl()
        this.validPic()
      }
    }
  }
</script>

<style scoped>
  .max-height {
    max-height: 300px;
    max-width: 100%;
  }
</style>